const app = getApp()
const { fetchVisitCode } = require('../../utils/api.js')
import Storage from '../../utils/storage'
Page({
	data: {
		search: "",
		currentCategory: 0,
    scrollTop: 0,
    categories: [],
    currentProducts: []
	},
	onLoad:function() {
		// 模拟数据加载
    	this.loadCategoryData()
	},
	// 输入事件处理函数
	onInputChange: function (e) {
		// e.detail.value 是输入框当前的值
		const value = e.detail.value;
    
		// this.setData({
		// 	inputValue: value // 更新 data 中的数据，同步到视图
		// });

		// 可以在这里进行实时搜索、校验等操作
		console.log('当前输入：', value);
	},
	// 加载分类和商品数据
  loadCategoryData: function() {
    // 模拟数据 - 实际开发中这里应该是从服务器获取
    const categories = [
      { id: 1, name: "热门推荐" },
      { id: 2, name: "手机数码" },
      { id: 3, name: "电脑办公" },
      { id: 4, name: "家用电器" },
      { id: 5, name: "食品生鲜" },
      { id: 6, name: "美妆护肤" },
      { id: 7, name: "服饰鞋包" },
      { id: 8, name: "母婴玩具" },
      { id: 9, name: "运动户外" },
      { id: 10, name: "图书文娱" }
    ];

    // 模拟商品数据
    const allProducts = this.generateMockProducts(categories);

    this.setData({
      categories: categories,
      allProducts: allProducts,
      currentProducts: allProducts[0] || []
    });
  },

  // 生成模拟商品数据
  generateMockProducts: function(categories) {
    const products = {};
    categories.forEach((category, index) => {
      products[index] = Array.from({ length: 12 }, (_, i) => ({
        id: `${category.id}-${i + 1}`,
        name: `${category.name}商品${i + 1}`,
        price: (Math.random() * 100 + 10).toFixed(2),
        sales: Math.floor(Math.random() * 1000),
        image: `http://127.0.0.1:2200/uploads/images/20251108/e9166c5c6eab66c72f6a566fc455f96d.jpeg`
      }));
    });
    return products;
  },

  // 切换分类
  switchCategory: function(e) {
    const index = e.currentTarget.dataset.index;
    
    if (this.data.currentCategory === index) {
      return;
    }

    this.setData({
      currentCategory: index,
      currentProducts: this.data.allProducts[index] || [],
      scrollTop: 0 // 重置右侧滚动位置
    });

    // 可以在这里添加分类切换的动画效果
    wx.vibrateShort(); // 轻微震动反馈
  },

  // 查看商品详情
  viewProductDetail: function(e) {
    const product = e.currentTarget.dataset.product;
    
    wx.showModal({
      title: product.name,
      content: `价格：¥${product.price}\n销量：${product.sales}件`,
      showCancel: false,
      confirmText: '知道了'
    });

    // 实际开发中应该跳转到商品详情页
    // wx.navigateTo({
    //   url: `/pages/product/detail?id=${product.id}`
    // });
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    // 模拟数据刷新
    setTimeout(() => {
      this.loadCategoryData();
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 1000);
  }
})